package com.lxf.cloudproduct.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lxf.cloudfeign.client.configsClient.ConfigClient;
import com.lxf.cloudfeign.client.otherClient.OtherClient;
import com.lxf.cloudfeign.client.productClient.ProductClient;
import com.lxf.cloudfeign.client.userClient.UserClient;
import com.lxf.cloudproduct.bean.ProductBean;
import com.lxf.cloudproduct.bean.ProductImgBean;
import com.lxf.cloudproduct.bean.TaskBean;
import com.lxf.cloudproduct.mapper.ProductItemRepository;
import com.lxf.cloudproduct.mapper.ProductMapper;
import com.lxf.cloudproduct.mapper.TaskMapper;
import com.lxf.cloudproduct.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * @author 罗兴发
 * @data 2025/5/9 9:54
 * @description：商品业务实现层
 */
@Service
@Slf4j
public class ProductServiceImpl implements ProductService {
    @Resource
    ProductMapper productMapper;
    @Resource
    TaskMapper taskMapper;

    //线程池配置
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    @Resource
    private ProductItemRepository productRepository;
    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Resource
    private ConfigClient configClient;

    @Resource
    private OtherClient otherClient;

    @Resource
    private UserClient userClient;

    @Resource
    private ProductClient productClient;

    //推荐数量
    private int RECOMMENDATIONS = 10;

    @Override
    @Transactional(rollbackFor = Exception.class)//开启事务
    public String addProduct(JSONObject json,HttpServletRequest request) {
        long l = System.currentTimeMillis();
        JSONObject js = new JSONObject();

        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        j1.put("name","商品");
        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);
        if (null!=o){
            //截取请求头中存储的用户ID
            int secretTokenIndex = secretToken.lastIndexOf(":");
            String userIdSub = secretToken.substring(secretTokenIndex+1);
            Integer userId = Integer.valueOf(userIdSub);//用户ID

            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String addTime = sf.format(new Date());

            //商品名称
            String goodName = json.getString("good_name");

            //商品库存
            Integer goodCount = json.getInteger("good_count");

            //商品单价
            BigDecimal goodPrice = json.getBigDecimal("good_price");

            //图片列表
            JSONArray jsonArray = json.getJSONArray("img_list");
            List<Map<String,Object>> lm = null;
            if (null!=jsonArray&&jsonArray.size()>0){
                ObjectMapper om = new ObjectMapper();
                try {
                    String s = om.writeValueAsString(jsonArray);
                    lm = om.readValue(s, List.class);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            //获取商品类型码
            Integer typeCode = userClient.getGoodCode(j1);
            ProductBean pb = new ProductBean();
            pb.setGoodCode("sp"+l);
            pb.setGoodName(goodName);
            pb.setGoodCount(goodCount);
            pb.setGoodPrice(goodPrice);
            pb.setUserId(userId);
            pb.setObjType(typeCode);
            pb.setAddTime(addTime);

            //list装载
            List<ProductBean> list = new ArrayList<>();
            list.add(pb);

            int flag = productMapper.addProduct(list);
            if (flag<0){
                js.put("code",401);
                js.put("msg","fails");
            }else {
                js.put("code",200);
                js.put("msg","Success");

                j1.put("keys",pb.getGoodCode());
                j1.put("data",goodCount);
                //新增redis中的商品数量
                userClient.addRedisData(j1);
                List<ProductImgBean> list1 = new ArrayList<>();
                if (null!=lm&&lm.size()>0){
                    for (Map m:lm){
                        Integer imgType = Integer.valueOf(String.valueOf(m.get("img_type")));
                        String imgUrl = String.valueOf(m.get("img_url"));
                        ProductImgBean imgBean = new ProductImgBean();
                        imgBean.setImgUrl(imgUrl);
                        imgBean.setImgType(imgType);
                        imgBean.setGoodCode(pb.getGoodCode());
                        imgBean.setAddTime(addTime);

                        //添加list
                        list1.add(imgBean);
                    }
                    pb.setImgList(list1);
                    //添加图片
                    productMapper.addProductImg(list1);
                }
                //存入es
                productRepository.save(pb);

                log.info("商品添加成功，共成功添加"+list1.size()+"张图片");
            }
        }else {
            js.put("code",400);
            js.put("msg","The Current Request is Invalid");
        }
        return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addProductDesc(JSONObject json, HttpServletRequest request) {
        JSONObject js = new JSONObject();

        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        j1.put("name","商品");
        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);
        if (null!=o){

            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String addTime = sf.format(new Date());

            // 商品编码
            String goodCode = json.getString("good_code");

            // 商品成分
            String component = json.getString("component");

            // 物流
            String logistics = json.getString("logistics");

            // 其他，，包括无理由退货等，商品质量问题等，是否包运费等
            String other = json.getString("other");



            //list装载
            List<ProductBean> list = new ArrayList<>();

            int flag = productMapper.addProduct(list);
            if (flag<0){
                js.put("code",401);
                js.put("msg","fails");
            }else {
                js.put("code",200);
                js.put("msg","Success");
            }
        }else {
            js.put("code",400);
            js.put("msg","The Current Request is Invalid");
        }
        return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String getProductByCode(JSONObject json,HttpServletRequest request) {
        JSONObject js = new JSONObject();
        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);
        Integer userId = null;
        if (null!=o){
            //截取请求头中存储的用户ID
            int secretTokenIndex = secretToken.lastIndexOf(":");
            String userIdSub = secretToken.substring(secretTokenIndex+1);
            userId = Integer.valueOf(userIdSub);//用户ID
        }

        //商品编码
        String goodCode = json.getString("good_code");
        //查询详情信息
        ProductBean product = productMapper.getProductByCode(goodCode);

        log.info("查询到的商品对象：{}",product);
        //创建一个JSON对象
        JSONObject j = new JSONObject();

        //公共部分
        j.put("user_id",userId);//用户ID
        j.put("obj_id",product.getGoodCode());//产品编号
        j.put("obj_type",product.getObjType());//产品类别

        if (null!=userId){
            //查询用户是否点赞该商品
            j.put("clr_type",0);//标识符：0点赞 1收藏
            String userCLRById = otherClient.getUserCLRById(j);
            JSONObject jsonObject = JSONObject.parseObject(userCLRById);
            product.setIsLike(jsonObject.getInteger("data"));

            //查询是否收藏
            j.put("clr_type",1);//标识符：0点赞 1收藏
            String userCLRById1 = otherClient.getUserCLRById(j);
            JSONObject jsonObject1 = JSONObject.parseObject(userCLRById1);
            product.setIsCollect(jsonObject1.getInteger("data"));
            //获取该用户对此商品的原有打分值，若无则返回0
            int userRating = userClient.getUserRatingById(j);

            //用户取消收藏等操作，需要将分数减一，所以此参数需要计算好传递过来
            userRating = userRating+1;
            //用户对该商品的最终打分
            j.put("user_rating",userRating);

            log.info("打分请求参数对象：{}",j);

            //每次访问详情，都需要将该商品打分值加一，以便推荐相关商品给用户
            userClient.addUserRating(j);
        }else {
            product.setIsLike(0);
            product.setIsCollect(0);
        }

        js.put("data",product);
        js.put("code",200);
        js.put("msg","Success");

        return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String getProduct(JSONObject json) {
        JSONObject js = new JSONObject();
        // 获取参数
        String goodName = json.getString("good_name");
        // 价格区间
        String price1 = json.getString("price1");
        if(null!=price1||!"".equals(price1)){
            price1 = new String("1");
        }
        String price2 = json.getString("price2");
        if (null!=price2||!"".equals(price2)){
            price2 = new String("9999999");
        }
        // 分页
        Integer page = json.getInteger("page");
        Integer size = json.getInteger("size");
        // 计算初始页
        Integer startPage = (page - 1) * size;

        // 1. 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(goodName, "goodName"))
                .withQuery(QueryBuilders.rangeQuery("goodPrice").gte(price1))
                .withQuery(QueryBuilders.rangeQuery("goodPrice").lte(price2))
                .withPageable(PageRequest.of(startPage, size));

        // 2. 添加高亮配置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("goodName")
                .preTags("<span style='color:red'>")
                .postTags("</span>");
        queryBuilder.withHighlightBuilder(highlightBuilder);

        // 3. 执行查询
        SearchHits<ProductBean> hits = elasticsearchRestTemplate
                .search(queryBuilder.build(), ProductBean.class);

        // 4. 处理高亮结果
        List<ProductBean> list = hits.stream()
                .map(hit -> {
                    ProductBean doc = hit.getContent();
                    Map<String, List<String>> highlightFields = hit.getHighlightFields();
                    highlightFields.forEach((field, texts) -> {
                        try {
                            Field declaredField = doc.getClass().getDeclaredField(field);
                            declaredField.setAccessible(true);
                            declaredField.set(doc, texts.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                    return doc;
                }).collect(Collectors.toList());
        // 7. 构造分页结果
        PageImpl<ProductBean> productBeans = new PageImpl<>(list, PageRequest.of(startPage, size), hits.getTotalHits());

        js.put("data",productBeans);
        js.put("code",200);
        js.put("msg","Success");

        return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//开启事务
    public String updateProductByCode(JSONObject json,HttpServletRequest request) {
        JSONObject js = new JSONObject();

        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);
        if (null!=o){
            //截取请求头中存储的用户ID
            int secretTokenIndex = secretToken.lastIndexOf(":");
            String userIdSub = secretToken.substring(secretTokenIndex+1);
            Integer userId = Integer.valueOf(userIdSub);//用户ID
            //商品编码
            String pCode = json.getString("pCode");
            //商品数量
            Integer pNum = json.getInteger("pNum");

            //上下架:0/1
            Integer isUp = json.getInteger("is_up");

            //更新操作
            int flag = productMapper.updateProductNumByCode(userId,pCode, pNum, isUp);
            if (flag<0){
                log.info("商品库存更新失败");
                js.put("code",401);
                js.put("msg","fails");
            }else {
                log.info("商品库存更新成功");
                js.put("code",200);
                js.put("msg","Success");
                j1.put("keys",pCode);
                j1.put("data",pNum);
                //更新redis的商品数量
                userClient.addRedisData(j1);
                ProductBean p = productMapper.getProductByCode(pCode);
                //更新es中的数量
                productRepository.save(p);
            }
        }else {
            js.put("code",400);
            js.put("msg","The Current Request is Invalid");
        }
        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public void updateProductNumByCode(JSONObject json) {
        //商品编码
        String pCode = json.getString("pCode");
        //商品数量
        Integer pNum = json.getInteger("pNum");
        int i = productMapper.updateProductNumByCode(null, pCode, pNum, null);
        if (i>=0) {
            JSONObject j = new JSONObject();
            j.put("keys",pCode);
            j.put("data",pNum);

            //更新redis数据
            userClient.addRedisData(j);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//开启事务
    public String deleteProductByCode(JSONObject json){
        JSONObject js = new JSONObject();
        JSONArray goodIdList = json.getJSONArray("good_id_list");
        List<String> list = JSONObject.parseArray(goodIdList.toJSONString(),String.class);
        JSONObject j1 = new JSONObject();
        //实现有返回值的线程池
        Future<String> submit = taskExecutor.submit(() -> {
            log.info("正在执行线程：" + Thread.currentThread().getName());
            try {
                int flag = productMapper.deleteProductByCode(list);
                if (flag<0)log.info("Delete Product Fails");
                else {
                    log.info("Delete Product Success");
                    for (int i = 0;i<list.size();i++){
                        j1.put("keys",list.get(i));
                        userClient.delRedisData(j1);
                        productRepository.deleteById(list.get(i));
                    }
                }
//                //同步删除转发，评论，评论点赞等数据信息
//                otherClient.del();

                Thread.sleep(2000);//睡眠两秒
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "线程：" + Thread.currentThread().getName() + "已执行完成";
        });
        log.info(""+submit);
        js.put("code",200);
        js.put("msg","success");
        return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
    }
    /**
     * 获取随机字符串
     * @return
     */
    private String generateUUID() {
        return cn.hutool.core.lang.UUID.randomUUID().toString().replaceAll(":", "").substring(0, 32);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)//开启事务
    public String uploadProduct(MultipartFile file,HttpServletRequest request) {
        JSONObject js = new JSONObject();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = sf.format(new Date());

        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        j1.put("name","商品");

        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);
        if (null!=o){
            //获取商品类型码
            Integer typeCode = userClient.getGoodCode(j1);
            //截取请求头中存储的用户ID
            int secretTokenIndex = secretToken.lastIndexOf(":");
            String userIdSub = secretToken.substring(secretTokenIndex+1);
            Integer userId = Integer.valueOf(userIdSub);//用户ID
            //空文件判断
            if (file.isEmpty()){
                //空文件直接返回
                js.put("code",401);
                js.put("msg","文件为空");
                return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
            }
            long l = System.currentTimeMillis();

            // 获取文件名
            String fileName = file.getOriginalFilename();

            //重组文件名称
            fileName = generateUUID() + "_" + fileName;

            //文件命名
            String basePath = new String(configClient.getUploadPath() + "/" + fileName);

            // 创建文件对象
            File dest = new File(basePath);
            //无返回值线程操作
            String finalFileName = fileName;
            //此处可往数据库中插入一条上传文件的任务，任务状态设置为上传中
            TaskBean task =  new TaskBean();
            task.setTContent("文件"+finalFileName+"-上传中.......");
            task.setUserId(userId);

            //list封装
            List<TaskBean> tList = new ArrayList<>();
            tList.add(task);

            //添加操作
            taskMapper.addTask(tList);
            //多线程解析Excel内容
            taskExecutor.execute(()->{
                try {
                    //若当前文件不存在，则创建
                    if (!dest.exists()) {
                        dest.createNewFile();
                    }
                    // 存储文件
                    file.transferTo(dest);

                    //解析
                    FileInputStream fileInputStream = new FileInputStream(dest);
                    //读取Excel文件
                    List<ProductBean> list = EasyExcel.read(fileInputStream).head(ProductBean.class).sheet().doReadSync();
                    if (null!=list){
                        for (ProductBean p:list) {
                            p.setUserId(userId);
                            p.setAddTime(addTime);
                            p.setObjType(typeCode);
                        }
                    }

                    int flag = productMapper.addProduct(list);

                    //无论成功或是失败，都需要将上传的文件删除
                    if (flag<0){
                        log.info("文件："+ finalFileName +"-解析失败，请检查网络后重试");

                        //解析失败，需将上传任务更新为失败状态
                        TaskBean uTask =  new TaskBean();
                        uTask.setTId(task.getTId());
                        uTask.setTContent("文件："+ finalFileName +"-解析失败，请检查网络后重试");
                        uTask.setUserId(userId);
                        uTask.setTStatus(2);
                        //更新状态
                        taskMapper.updateTask(uTask);

                        //删除文件
                        deleteFile(basePath);
                    }else {
                        log.info("文件："+ finalFileName +"-解析完成");

                        //解析成功，需将上传任务更新为完成状态
                        TaskBean uTask =  new TaskBean();
                        uTask.setTId(task.getTId());
                        uTask.setTContent("文件："+ finalFileName +"-解析完成");
                        uTask.setUserId(userId);
                        uTask.setTStatus(1);
                        //更新状态
                        taskMapper.updateTask(uTask);

                        //删除文件
                        deleteFile(basePath);

                        //redis中存储库存信息
                        for (ProductBean p:list) {
                            j1.put("keys",p.getGoodCode());
                            j1.put("data",p.getGoodCount());
                            //添加库存
                            userClient.addRedisData(j1);
                            //存入es中
                            productRepository.save(p);
                        }
                    }
                    log.info("上传花费时间（单位：毫秒）：{}",l);
                    Thread.sleep(200);
                }catch (Exception e){
                    e.printStackTrace();
                }
            });
            js.put("code",201);
            js.put("msg","Analyzing...Please Wait!");
        }else {
            js.put("code",400);
            js.put("msg","The Current Request is Invalid");
        }
        return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String updateProductImgByCode(JSONObject json, HttpServletRequest request) {
        JSONObject js = new JSONObject();

        String goodCode = json.getString("good_code");//商品编码

        // 根据商品编码清空该商品图片列表
        productMapper.deleteProductImgByCode(goodCode);

        // 时间规格化
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = sf.format(new Date());

        // 根据商品编码获取商品详情
        ProductBean pb = productRepository.findById(goodCode).get();

        JSONArray jsonArray = json.getJSONArray("img_list");//图片集合
        ObjectMapper om = new ObjectMapper();
        List<Map<String,Object>> lm = null;
        try {
            String s = om.writeValueAsString(jsonArray);
            lm = om.readValue(s, List.class);
        }catch (Exception e){
            e.printStackTrace();
        }

        // 装载商品图片信息
        List<ProductImgBean> list1 = new ArrayList<>();
        for (Map m:lm){
            Integer imgType = Integer.valueOf(String.valueOf(m.get("img_type")));
            String imgUrl = String.valueOf(m.get("img_url"));
            ProductImgBean imgBean = new ProductImgBean();
            imgBean.setImgUrl(imgUrl);
            imgBean.setImgType(imgType);
            imgBean.setGoodCode(pb.getGoodCode());
            imgBean.setAddTime(addTime);

            // 添加list
            list1.add(imgBean);
        }
        pb.setImgList(list1);
        // 添加图片
        int flag = productMapper.addProductImg(list1);
        if (flag<0){
            js.put("code",401);
            js.put("msg","Fails");
        }else {
            js.put("code",200);
            js.put("msg","Success");
            // 存入es
            productRepository.save(pb);
        }

        return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String deleteProductEsData() {
        JSONObject js = new JSONObject();

        //删除es
        productRepository.deleteAll();

        js.put("code",200);
        js.put("msg","Success");

        return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String recommendProduct(JSONObject json, HttpServletRequest request) {
        JSONObject js = new JSONObject();

        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        j1.put("name","商品");
        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);
        if (null!=o){
            //截取请求头中存储的用户ID
            int secretTokenIndex = secretToken.lastIndexOf(":");
            String userIdSub = secretToken.substring(secretTokenIndex+1);
            Integer userId = Integer.valueOf(userIdSub);//用户ID

            //需要推荐的类别
            Integer type = json.getInteger("obj_type");

            //推荐数量
            Integer recommendations = RECOMMENDATIONS;
            //默认推荐点赞、收藏、评论最多的商品
            j1.put("num",recommendations);
            j1.put("user_id",userId);
            j1.put("obj_type",type);

            //装载查询数据的ID集合
            List<String>  l = new ArrayList<>();

            //获取最终推荐数据ID
            List<String> list = userClient.getRecommend(j1);
            if (list.size()>0){
                for (int i=0; i<list.size(); i++){
                    String s = list.get(i);

                    //返回的结果集中包含了事物ID和事务类型拼接，
                    // 如：ceshi10（其中ceshi1为商品编码，0为类型编码），
                    // 需要将最后一个字符分割掉
                    StringBuilder sb = new StringBuilder(s);
                    sb.deleteCharAt(s.length() - 1);
                    String productId = sb.toString();

                    //加入list中，批量查询
                    l.add(productId);
                }
            }else {

                //查询相应的商品信息
                String s = productClient.findAllByCLR(j1);
                JSONObject j2 = JSONObject.parseObject(s);
                JSONArray jsonArray = j2.getJSONArray("goodCodeList");
                for (int i=0;i<jsonArray.size();i++){
                    l.add(jsonArray.getString(i));
                }
            }

            //请求参数
            JSONObject j = new JSONObject();
            j.put("good_code_list",l);
            //批量查询
            String f = productClient.findAllByGoodCodeIn(j);
            JSONObject j2 = JSONObject.parseObject(f);
            JSONArray data = j2.getJSONArray("data");

            log.info("商品推荐成功");
            js.put("data",data);
            js.put("code",200);
            js.put("msg","Success");
        }else {
            js.put("code",400);
            js.put("msg","The Current Request is Invalid");
        }
        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String getProductImgByCode(JSONObject json) {
        JSONObject js = new JSONObject();

        //获取参数
        String goodCode = json.getString("good_code");

        //根据编码获取图片
        List<ProductImgBean> list = productMapper.getProductImgByCode(goodCode);

        js.put("data",list);
        js.put("code",200);
        js.put("msg","Success");
        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String findAllByGoodCodeIn(JSONObject json) {
        JSONObject js = new JSONObject();

        JSONArray jsonArray = json.getJSONArray("good_code_list");
        List<String> list = JSONObject.parseArray(jsonArray.toJSONString(),String.class);

        //数据查询
        List<ProductBean> productList = productMapper.findAllByGoodCodeIn(list);

        js.put("code",200);
        js.put("msg","Success");
        js.put("data",productList);
        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String findAllByCLR(JSONObject json) {
        JSONObject js = new JSONObject();

        Integer num = json.getInteger("num");

        //数据查询
        List<ProductBean> productList = productMapper.findAllByCLR(num);

        //装载商品编码的集合
        List<String> l = new ArrayList<>();
        for (ProductBean b:productList) {
            l.add(b.getGoodCode());
        }

        js.put("code",200);
        js.put("msg","Success");
        js.put("data",productList);
        js.put("goodCodeList",l);
        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    /**
     * 删除目录文件
     * @param filePath
     */
    private void deleteFile(String filePath){
        File file = new File(filePath);
        if (file.exists()){
            //调用该方法不占用资源,该方法只会在jvm结束后进行删除，不会立刻进行删除操作
            file.deleteOnExit();
            log.info("已标记需要删除的上传文件信息，带JVM正常退出后进行删除");
        }
    }
}
